package com.financing.controller.user;
import java.util.Map;

import com.financing.model.Data;
import com.financing.model.invest.Trade;
import com.financing.model.user.User;
import com.financing.model.user.UserReferee;
import com.financing.service.invest.TradeService;
import com.financing.service.user.UserRefereeService;
import com.financing.util.AES;
import com.financing.util.Json;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;

/**
 *  用户邀请控制器
 * @since 2017-06-06
 * @author 无处不在的二叔
 */
public class UserRefereeController extends Controller {
	private TradeService trade = new TradeService();
	private UserRefereeService userReferee = new UserRefereeService();
	
	
	public void myList() throws Exception {    

		User u = getAttr("user");
		int page = getParaToInt("page",1);
		int size = getParaToInt("size",10);
		int aes = getParaToInt("aes",1);
		Map<String, String> params = Data.flat(getParaMap());
		params.put("refereeId", String.valueOf(u.getId()));
		Page<UserReferee> p = userReferee.list(page, size, params);
		
		p.getList().forEach(n->{
			
			User user = User.me.findById(n.getUserId());
			User inviter = User.me.findById(n.getRefereeId());
			
			if(user!=null && inviter!=null) {
				n.put("user_real_name", user.getRealName());
				n.put("user_create_time", user.getCreateTime());
				
				n.put("referee_real_name", inviter.getRealName());
				n.put("referee_create_time", inviter.getCreateTime());
				
				/**获取首笔投资记录*/
				Trade t = trade.findFirst(n.getUserId());
				n.put("tradeName", t!=null?t.getBidName():"暂无交易");
				n.put("tradeAmount", t!=null?t.getAmount():"0.0");			
				
				if(aes==1) {
					n.setMobile(AES.encode(n.getMobile()));
					n.setRefereeMobile(AES.encode(n.getRefereeMobile()));
				}
			}
		});
		
		// 获取推荐总金额
		double total = userReferee.totalRefereeShare(u.getId());
		
		renderJson(Json.ok("信息获取成功！", Data.put("total",String.valueOf(total),"page",p)));
	}
    
	/**
	 * 获取所有邀请记录
	 */
	public void list() {
		int page = getParaToInt("page",1);
		int size = getParaToInt("size",10);
		
		Map<String,String> params = Data.flat(getParaMap());
		Page<UserReferee> p = userReferee.list(page, size, params);
		
		p.getList().forEach(n->{
			
			User user = User.me.findById(n.getUserId());
			n.put("user_real_name", user.getRealName());
			n.put("user_create_time", user.getCreateTime());
			
			User inviter = User.me.findById(n.getRefereeId());
			n.put("referee_real_name", inviter.getRealName());
			n.put("referee_create_time", inviter.getCreateTime());
			
			// 获取首笔投资记录
			Trade t = trade.findFirst(n.getUserId());
			n.put("tradeName", t!=null?t.getBidName():"暂无交易");
			n.put("tradeAmount", t!=null?t.getAmount():"0.0");
		});
		
		renderJson(Json.ok("信息获取成功！", Data.put("page",p)));
	}
}
 